package domainofratingsindexer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;



/**
 * @author Martin Mihalovic
 */
public class DomainOfRatingsIndexer {

    private static String indexFileName;
    private BufferedWriter writer;

    
    /**
     * @param args destination file
     */
    public static void main(String[] args) throws IOException, SQLException, Exception {
        
        if(args.length == 1) {
            indexFileName = args[0];
            File file = new File(indexFileName);
            
            if(!file.exists())
                file.createNewFile();
            
            if(!file.exists() || !file.isFile() || !file.canWrite()) {
                System.err.println("Cannot find or access file " + indexFileName);
                return;
            }
        }
        
        DomainOfRatingsIndexer indexer = new DomainOfRatingsIndexer();
        indexer.createIndex();
        System.out.print("Finished. Press ENTER to quit");
        System.in.read();
    }
    
    

    private void createIndex() throws IOException, SQLException, Exception {
        DataAccess data = new DataAccess();
        writer = new BufferedWriter(new FileWriter(indexFileName));
        
        List<String> domainIDs = data.GainDomains();
        for(String id : domainIDs) {
            List<UserRating> ratings = data.GainPositiveRatingsInDomain(id);
            int[] toBeSaved = new int[ratings.size()];
            int counter=0;
            for(UserRating rating : ratings) {
                if(!rating.DomainId.equals(id))
                    throw new Exception("Incorrect domain ID");
                toBeSaved[counter] = rating.RatingId;
                counter++;
            }
            
            saveRatingsOfDomain(id, toBeSaved);
            System.out.println("Domain " + id + ": " + toBeSaved.length + " 'usefull' ratings saved.");
        }
        
        writer.close();
    }
    
    
    private void saveRatingsOfDomain(String domainId, int[] ratings) throws IOException {
        writer.write(domainId + "::");
        for(int rating : ratings)
            writer.write(rating + ",");

        writer.newLine();
    }
}
